package org.system.core.controller.monitor;

import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.system.core.annotation.Log;
import org.system.core.common.PageResult;
import org.system.core.common.Result;
import org.system.core.domain.entity.SysLoginInfo;
import org.system.core.enums.BusinessType;
import org.system.core.service.monitor.SysLoginInfoService;
import org.system.core.service.system.SysPasswordService;
import org.system.core.utils.PageUtils;

import java.util.List;

/**
 * @author baoRoot
 */
@RestController
@Api(tags = {"登录日志模块"})
@RequestMapping("/monitor/loginInfo")
public class SysLoginInfoController {

    private static final Logger logger = LoggerFactory.getLogger(SysLoginInfoController.class);

    @Autowired
    private SysLoginInfoService sysLoginInfoService;

    @Autowired
    private SysPasswordService sysPasswordService;

    @GetMapping("/list")
    @ApiOperation("获取登录日志列表")
    @PreAuthorize("@ss.hasPermi('monitor:loginInfo:list')")
    public PageResult<SysLoginInfo> list(SysLoginInfo sysLoginInfo) {
        logger.info("获取登录日志列表: {}", sysLoginInfo);
        PageUtils.startPage();
        List<SysLoginInfo> sysLoginInfos = sysLoginInfoService.selectLoginInfoList(sysLoginInfo);
        return PageResult.ok(new PageInfo<>(sysLoginInfos));
    }

    @ApiOperation("删除登录日志")
    @DeleteMapping("/{infoIds}")
    @Log(title = "登录日志", businessType = BusinessType.DELETE)
    @PreAuthorize("@ss.hasPermi('monitor:loginInfo:remove')")
    public Result<String> deleteLoginInfo(@PathVariable Long[] infoIds) {
        logger.info("删除登录日志: {}", infoIds);
        sysLoginInfoService.deleteLoginInfoByIds(infoIds);
        return Result.ok();
    }

    @ApiOperation("清空登录日志")
    @DeleteMapping("/clean")
    @Log(title = "登录日志", businessType = BusinessType.CLEAN)
    @PreAuthorize("@ss.hasPermi('monitor:loginInfo:remove')")
    public Result<String> cleanLoginInfo() {
        logger.info("清空登录日志");
        sysLoginInfoService.cleanLoginInfo();
        return Result.ok();
    }

    @ApiOperation("解锁账户")
    @GetMapping("/unlock/{userName}")
    @PreAuthorize("@ss.hasPermi('monitor:loginInfo:unlock')")
    @Log(title = "账户解锁", businessType = BusinessType.OTHER)
    public Result<String> unlock(@PathVariable("userName") String userName) {
        logger.info("解锁账户: {}", userName);
        sysPasswordService.clearLoginRecordCache(userName);
        return Result.ok();
    }

}
